package com.gitee.sop.adminserver.common;

import com.gitee.easyopen.ApiContext;
import com.gitee.easyopen.session.ApiHttpSession;
import com.gitee.easyopen.session.ApiSessionManager;
import com.gitee.sop.adminserver.entity.AdminUserInfo;
import com.gitee.sop.adminserver.freeway.api.ums.UmUserService;
import com.gitee.sop.adminserver.freeway.bean.ums.UserResult;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import static com.gitee.easyopen.ApiContext.*;

public class WebContext {
    private static WebContext INSTANCE = new WebContext();

    private static final String S_USER = "s_user";

    private UmUserService umUserService;

    private WebContext() {
    }

    public static WebContext getInstance() {
        return INSTANCE;
    }

    /**
     * 获取当前登录用户
     *
     * @return
     */
    public AdminUserInfo getLoginUser() {
        String sessionId = getSessionId();
        if (sessionId == null) {
            return null;
        }
        HttpSession session = getSessionManager().getSession(sessionId);
        if (session == null) {
            return null;
        }
        return (AdminUserInfo) session.getAttribute(S_USER);
    }

    public void setLoginUser(HttpSession session, AdminUserInfo user) {
        if (session != null) {
            session.setAttribute(S_USER, user);
        }
    }

    public void setUMLoginUser(HttpSession session,UserResult userResult){
        session.setAttribute(S_USER,userResult);
    }

    public UserResult getUMLoginUserUm() {
        String sessionId = getSessionId();
        if (sessionId == null) {
            return null;
        }

        HttpSession session = getSessionManager().getSession(sessionId);
        if (session == null) {

            //解决分布式token问题

            String hcp = sessionId;
            UserResult userResult = this.umUserService.getByToken(hcp);

            if(userResult!=null) {
                ServletContext servletContext = getServletContext();
                session = new ApiHttpSession(servletContext, sessionId);

                ApiSessionManager apiSessionManager = (ApiSessionManager) ApiContext.getSessionManager();

                session.setMaxInactiveInterval(apiSessionManager.getSessionTimeout());
                apiSessionManager.getCache().put(session.getId(), session);


                session.setAttribute(S_USER,userResult);
            }



        }

        return (UserResult) session.getAttribute(S_USER);
    }

    public void setUmUserService(UmUserService umUserService){
        if(umUserService==null) {
            this.umUserService = umUserService;
        }
    }

}
